package com.app.micaihu.view.newsdetail;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.adapter.NewsAdapter;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseListActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.news.TopicNewsList;
import com.app.micaihu.bean.news.TopicsInforBean;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.LoadMoreView;
import com.app.micaihu.listener.AutoHeightControllerListener;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.AppShareUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.google.gson.reflect.TypeToken;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Guo on 2016/8/29.
 * <p/>
 * 新闻专题的列表
 */
public class NewsTopicsActivity extends BaseListActivity<NewsEntity> implements AbsListView.OnScrollListener {


    private CustomImageView civBanner;
    private View view;
    private View viewAbout;//相关推荐
//    private View viewSticky;//悬浮view
    private String articleId;//当前的专题ID
    private AppShareUtils mShareUtils;//分享工具
    private TopicsInforBean articleInfo;
    private TextView tvAbout;
    private String articleNum;
    private String notice;
    private TextView tvSticky;
    private LoadMoreView loadMoreView;
    private boolean isNoMroe;
    private TopicNewsList topicsEntity;
    private AutoHeightControllerListener mAutoHeightControllerListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent != null) {
            articleId = intent.getStringExtra(Config.Extra.PARAMETER1);
            if (TextUtils.isEmpty(articleId)) {
                ToastUtils.makeText(getResources().getString(R.string.dataerror));
                finish();
            }
        }
        super.onCreate(savedInstanceState);


    }

    @Override
    protected void changeView() {
        super.changeView();
        ImageView moreView = setTitleRightImage(R.drawable.detail_menu_black_selector);
        moreView.setOnClickListener(this);
        if (mListView != null) {
            view = LayoutInflater.from(this).inflate(R.layout.layout_topics_head, null);
            civBanner = (CustomImageView) view.findViewById(R.id.civ_banner);
            mListView.getRefreshableView().addHeaderView(view);

            viewAbout = LayoutInflater.from(this).inflate(R.layout.layout_topics_about, null);
            tvAbout = (TextView) viewAbout.findViewById(R.id.tv_about);
            mListView.getRefreshableView().addHeaderView(viewAbout);

          /*  viewSticky = LayoutInflater.from(this).inflate(R.layout.layout_topics_about, null);
            tvSticky = (TextView) viewSticky.findViewById(R.id.tv_about);
            RelativeLayout viewContainer = (RelativeLayout) findViewById(R.id.rl_baselistactivity_container);
            viewSticky.setVisibility(View.GONE);
            viewContainer.addView(viewSticky);
*/

            loadMoreView = new LoadMoreView(this);
            loadMoreView.setErrorPageOnClickListener(this);
            mListView.getRefreshableView().addFooterView(loadMoreView);
            loadMoreView.setVisibility(View.GONE);
            mListView.setOnScrollListener(this);
        }

    }


    @Override
    protected void changeData(final boolean isRefresh) {
        Map<String, String> params = new HashMap<>();
        if (UserInforManager.getInstance().isLogin()) {
            params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        } else {
            params.put("uid", "0");
        }

        params.put("speicalId", articleId);
        params.put("page", dataPage + "");
        HttpListener<DataBean<TopicNewsList>> topicsListener = new HttpListener<DataBean<TopicNewsList>>() {


            @Override
            public void onStart() {

                setLoadView(LOADING,null);
            }

            @Override
            public void onError(VolleyError error) {

                setLoadView(NO_NET,AppApplication.getInstance().getString(R.string.neterror_click));


            }

            @Override

            public void onSuccess(DataBean<TopicNewsList> response) {
                if (response.noError() && response.getData() != null) {
                    topicsEntity = response.getData();
                    if (topicsEntity != null) {
//                        initBanner(topicsEntity);
                        List<NewsEntity> newsList = topicsEntity.getNewsList();
                        if (newsList != null && newsList.size() > 0) {
                            if (dataList == null) {
                                dataList = new ArrayList<NewsEntity>();
                            }
                            if (isRefresh) {
                                //清空数据
                                initBanner(topicsEntity);//适配头部
                                dataList.clear();
                            }
                            dataList.addAll(newsList);

                            if (mAdapter == null) {
                                mAdapter = new NewsAdapter(dataList, mActivity, null);
                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.notifyDataSetChanged();
                            }

                            setLoadView(LOADSUCES,null);

                        } else {
                            if (dataList != null && dataList.size() > 0) {

                                setLoadView(LOADSUCES,getResources().getString(R.string.homepage_msg_nomoremsg));
                                loadMoreView.setVisibility(View.VISIBLE);
                                loadMoreView.showErrorPage(getResources().getString(R.string.homepage_msg_nomoremsg));
                                loadMoreView.setEmptyPageOnClickListener(null);
                            } else {
                                //updateLoadView(DATAERROR, response.getNnderstoodMsg());
                                setLoadView(DATAERROR,response.getNnderstoodMsg());
                            }
                        }
                    }
                } else {
//                    updateLoadView(DATAERROR, response.getNnderstoodMsg());
                    setLoadView(DATAERROR,response.getNnderstoodMsg());
                }
            }
        };

        addPostCacheRequest(URIContant.TOPICS_NEWS, new TypeToken<DataBean<TopicNewsList>>() {
        }.getType(), params, topicsListener);

    }

    /**
     * 初始化banner 的头部
     *
     * @param topicsEntity
     */
    private void initBanner(TopicNewsList topicsEntity) {
        articleInfo = topicsEntity.getArticleInfo();
        if (articleInfo == null || TextUtils.isEmpty(articleInfo.getBanner())) {
            view.setVisibility(View.GONE);
        } else {
            view.setVisibility(View.VISIBLE);

            if(mAutoHeightControllerListener == null){
                mAutoHeightControllerListener = new AutoHeightControllerListener(civBanner);

            }

            LoadImageUtils.getInstance().loadImage(civBanner, articleInfo.getBanner(), mAutoHeightControllerListener);

            articleNum = articleInfo.getArticleNum();
            notice = articleInfo.getNotice();
            tvAbout.setText(notice);
        }


    }


    @Override
    public void onClick(View view) {
        if (view == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.error_page:// 重新加载页面数据
                if (mListView.isRefreshing())
                    break;
                changeData(true);
                break;
            case R.id.page_head_function:
                share();
                break;
            default:

                break;
        }
    }


    /**
     * 分享
     */
    private void share() {
        initShare();
        mShareUtils.showShareDialog(this.articleInfo,TypeConstant.PAGE_NEWS);
    }


    /**
     * 初始化分享工具
     */
    private void initShare() {
        if (mShareUtils == null) {
//            SlideSelectView.onSelectListener selectListener = new SlideSelectView.onSelectListener() {
//                @Override
//                public void onSelect(int textSize) {
//                    UserConfigTools.textSize = textSize;
//                    AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.option_textSize, UserConfigTools.textSize);
//                    //初始化handler
//                    if (topicsEntity == null) {
//                        return;
//                    }
////                    mWebView.loadDataWithBaseURL(null, mNewsContent.getArticleContent(), "text/html", "utf-8", null);// 网页刷新
//                }
//            };
            mShareUtils = new AppShareUtils(this);
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //因为有头部
        if (mListView.getRefreshableView().getHeaderViewsCount() > 0) {
            position = position - mListView.getRefreshableView().getHeaderViewsCount();
        }
        //防止越界
        if (position >= dataList.size()) {
            position = dataList.size() - 1;
        } else if (position < 0) {
            //position = 0;
            return;
        }
        NewsEntity news = dataList.get(position);
        if (news == null) {
            return;
        }
        TypeConstant.openTypeDetail(news,this,TypeConstant.SOURCETYPE_NORMAL);
        //添加已读文章id
        TextView textView = (TextView) view.findViewById(R.id.item_public_title);
        if (textView != null) {
            textView.setEnabled(false);
        }
        //添加已读新闻
        NewsAdapter.addReadList(news.getArticleId());

    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //当滑动停止并且滑动到底部时加载更多数据
        /*if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
            if (view.getLastVisiblePosition() >= (view.getAdapter().getCount() - 2)) {
                if (!mListView.isRefreshing() && !isNoMroe) {

                    dataPage++;
                    LogUtils.e("gzq","是否有更多="+isNoMroe+"--当前页数=="+dataPage);
                    changeData(false);
                } else {
                    loadMoreView.setVisibility(View.VISIBLE);
                    loadMoreView.showErrorPage(getResources().getString(R.string.common_nomore));
                    loadMoreView.setEmptyPageOnClickListener(null);
                }

            }
        }*/

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
       /* if (firstVisibleItem >= 2) {
            viewSticky.setVisibility(View.VISIBLE);
        } else {

            viewSticky.setVisibility(View.GONE);
        }

*/
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //设置友盟回调
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
